package com.foreveross.chameleon.manager.task;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Set;
import java.util.zip.ZipException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.darin.cl.http.CLHttpProgressImpl;
import com.darin.cl.http.CLHttpUtil;
import com.darin.cl.http.CLHttpUtil.RequestMethod;
import com.darin.cl.task.CLTask;
import com.darin.cl.util.CLFileUtil;
import com.foreveross.URL;
import com.foreveross.chameleon.manager.AutoDownloadHelper;
import com.foreveross.chameleon.manager.BroadCastManager;
import com.foreveross.chameleon.manager.CubeContentManager;
import com.foreveross.chameleon.manager.CubeContentStatus;
import com.foreveross.pojo.CubeContent;
import com.foreveross.pojo.CubeModule;
import com.foreveross.pojo.CubeModuleDownloadInfo;

public class UpgradeModuleTask extends CLTask<Object, Object, String> {

	private CubeModuleDownloadInfo mBean = null;
	private CLHttpUtil mClHttpUtil;
	private Context mContext;
	private CubeModule oldCubeModule;

	public UpgradeModuleTask(CubeModuleDownloadInfo bean, CLHttpUtil clHttpUtil,
			Context context) {
		super();
		this.mBean = bean;
		this.mContext = context;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		CubeModule module = mBean.getModule();
		module.setModuleType(CubeModule.UPGRADING);
		CubeContentStatus contentStatus = CubeContentManager.getInstance().getmCubeContentStatus();
		oldCubeModule = contentStatus
				.getIdentifier_old_version_map()
				.get(module.getIdentifier());
		if (!module.isHidden()) {
			contentStatus.removeFormMain(oldCubeModule);
			contentStatus.add2Main(module);
			if (isExist(mContext, oldCubeModule, "icon.img")) {
				module.setIcon(URL.getSdPath(mContext, module.getIdentifier()
						+ "/icon.img"));
			} else if (isExist(mContext, oldCubeModule, "icon.png")) {
				module.setIcon(URL.getSdPath(mContext, module.getIdentifier()
						+ "/icon.png"));
			}
		}
		BroadCastManager.sentModuleDownloadCount(mContext);
	}

	@Override
	public String doInBackground(Object... params) throws Exception {
		mClHttpUtil = new CLHttpUtil(mBean.getDownloadUrl());
		mClHttpUtil.downloadFile(mBean.getFilePath(), RequestMethod.GET, null,
				new CLHttpProgressImpl() {

					@Override
					public void onProcessChange(long process, long max,
							Object flag) {
						MathContext mc = new MathContext(3,
								RoundingMode.HALF_DOWN);
						BigDecimal db1 = new BigDecimal(process);
						BigDecimal db2 = new BigDecimal(max);
						BigDecimal result = (db1.divide(db2, mc).multiply(
								new BigDecimal(100), mc));
						if (process < max) {
							mBean.getModule().setProgress(result.intValue());
							BroadCastManager.updateProgress(mContext,
									mBean.getModule(), result.intValue());
						} else {
							mBean.setDownSuccess(true);
						}

					}

					@Override
					public void onProcessEnd() {
						// 下载完成后进行解压操作
						boolean unZip = false;
						CubeModule module = mBean.getModule();
						// 先删除旧文件
						String basePath = Environment
								.getExternalStorageDirectory().getPath()
								+ "/"
								+ URL.APP_PACKAGENAME;
						StringBuilder sb2 = new StringBuilder();
						sb2.append(basePath).append("/www/")
								.append(module.getIdentifier());
						CLFileUtil.deleteFolder(sb2.toString());
						try {
							CLFileUtil.unZipFile(mBean.getFilePath(),
									mBean.getFileDir());
							unZip = true;
						} catch (ZipException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// 解压成功后改变模块状态
						CubeModule oldModule = oldCubeModule;
						CubeContent cubeContent =CubeContentManager.getInstance().getCubeContent();
						CubeContentStatus contentStatus = CubeContentManager.getInstance()
								.getmCubeContentStatus();
						if (unZip) {
							module.setModuleType(CubeModule.INSTALLED);
							module.setUpdatable(false);
							if (isExist(mContext, module, "icon.img")) {
								module.setIcon(URL.getSdPath(mContext,
										module.getIdentifier() + "/icon.img"));
							} else if (isExist(mContext, module, "icon.png")) {
								module.setIcon(URL.getSdPath(mContext,
										module.getIdentifier() + "/icon.png"));
							}
							oldModule.setModuleType(CubeModule.INSTALLED);
							if (isExist(mContext, module, "icon.img")) {
								oldModule.setIcon(URL.getSdPath(mContext,
										module.getIdentifier() + "/icon.img"));
							} else if (isExist(mContext, module, "icon.png")) {
								oldModule.setIcon(URL.getSdPath(mContext,
										module.getIdentifier() + "/icon.png"));
							}

							oldModule.setUpdatable(false);
							contentStatus
									.removeFormUpdatable(module);
							contentStatus
									.removeFormInstalled(oldModule);
							contentStatus.add2Installed(
									module);
							contentStatus
									.getIdentifier_new_version_map()
									.remove(module.getIdentifier());
							contentStatus
									.getIdentifier_old_version_map()
									.remove(oldModule.getIdentifier());
							contentStatus.getAllSet()
									.remove(oldModule);

							Set<CubeModule> storedSet = cubeContent
									.getModules();
							cubeContent.getOldUpdateModules().remove(
									oldModule.getIdentifier());
							storedSet.remove(oldModule);
							storedSet.add(module);
							CubeContentManager.getInstance().save(mContext,
									cubeContent);
							BroadCastManager.refreshModule(mContext, "upgrade",
									module);
							BroadCastManager.updateProgress(mContext, module,
									101);
							Log.v("Depends", "升级成功，开始检查依赖");
							AutoDownloadHelper.getInstance().finishDownload(
									module, true);
							BroadCastManager.sentModuleDownloadCount(mContext);
							if (AutoDownloadHelper.getInstance()
									.getProgressCount() == 0) {
								BroadCastManager
										.sentModuleDownloadFinsh(mContext);
								AutoDownloadHelper.getInstance().clear();
							}

							ArrayList<CubeModule> result = CubeContentManager
									.getInstance().checkDepends(
											module.getIdentifier());
							for (CubeModule m : result) {
								if (m.getPrivileges() != null) {
									CubeContentManager.getInstance()
											.downLoadOrUpgradeModule(m,
													mContext);
								}
							}

						} else {
							module.setModuleType(CubeModule.UPGRADABLE);
							module.setUpdatable(true);
							oldModule.setModuleType(CubeModule.INSTALLED);
							oldModule.setUpdatable(true);
							if (!module.isHidden()) {
								contentStatus.removeFormMain(
										module);
								contentStatus.add2Main(
										oldModule);
								if (isExist(mContext, module, "icon.img")) {
									oldModule.setIcon(URL.getSdPath(mContext,
											module.getIdentifier()
													+ "/icon.img"));
								} else if (isExist(mContext, module, "icon.png")) {
									oldModule.setIcon(URL.getSdPath(mContext,
											module.getIdentifier()
													+ "/icon.png"));
								}
							}
							AutoDownloadHelper.getInstance().finishDownload(
									module, false);
							BroadCastManager.sentModuleDownloadCount(mContext);
							if (AutoDownloadHelper.getInstance()
									.getProgressCount() == 0) {
								BroadCastManager
										.sentModuleDownloadFinsh(mContext);
							}
							Toast.makeText(mContext, "网络状态不稳定!",
									Toast.LENGTH_SHORT).show();
						}
						BroadCastManager.refreshMainPage(mContext, module);
						BroadCastManager.updateProgress(mContext, module, 101);
					}

				});

		return null;
	}

	@Override
	public void doOnSuccess(String result) {

	}

	@Override
	protected void doOnException(Exception exception) {
		// TODO Auto-generated method stub
		super.doOnException(exception);
	}

	@Override
	protected void onFinish() {
		// TODO Auto-generated method stub
		super.onFinish();
		mClHttpUtil.shutdown();
	}

	public boolean isExist(Context context, CubeModule cubeModule, String name) {
		String path = URL.getSdPath(context, cubeModule.getIdentifier()) + "/"
				+ name;
		File f = new File(path);
		if (f.exists()) {
			return true;
		} else {
			return false;
		}
	}

}
